/**
 * Created by xiaomin on 2015/6/18.
 */

var userController = angular.module('userController', ['BaseService', 'PrivilegeService']);

var URL = {
    USER_ADD: '/admin/user/add',
    USER_LIST: '/admin/user/list',
    USER_DELETE: '/admin/user/delete',
    USER_DEL_BAH: '/admin/user/batch/delete',
    USER_LOGIN: '/login',
    USER_LOGOUT: '/login_out',
    USER_UNIQUE: '/admin/user/unique',
    USER_UPDATE: '/admin/user/update',
    USER_GETPRIV: '/admin/user/get/privilege',
    ROLE_ADD: '/admin/role/add',
    ROLE_LIST: '/admin/role/list',
    ROLE_DELETE: '/admin/role/delete',
    ROLE_DEL_BAH: '/admin/role/batch/delete',
    ROLE_PRIV: '/admin/role/add/privilege',
    ROLE_UNIQUE: '/admin/role/unique',
    ROLE_UPDATE: '/admin/role/update',
    PRIV_ADD: '/admin/privilege/add',
    PRIV_DELETE: '/admin/privilege/delete',
    PRIV_LIST: '/admin/privilege/list',
    PRIV_DEL_BAH: '/admin/privilege/batch/delete'

};

/**
 * 获取列表的公共函数
 * @param service 请求服务
 * @param url   请求地址
 * @param scope 控制器作用域
 * @param type
 * @param state
 */
function getList(service, url, scope, type, state) {
    service.getList(url).then(function (res) {
        scope.show = false;
        if (res.code == 0) {
            scope[type] = res.page.data;
        } else if (res.code == 2) {
            state.go("login");
        } else if (res.code == 3) {
            scope.message = "您没有操作权限哦~~"
        } else {
            state.go("login");
        }
    }, function (err) {
        console.log(err);
    });
}

/**
 * 删除一条数据公共函数
 * @param service 请求服务
 * @param url   请求地址
 * @param id    删除id
 * @param callback  回调函数
 */
function del(service, url, id, callback) {
    service.delete(url, {uid: id}).then(function (res) {
        if (res.code == 0) {
            callback();
        } else if (res.code == 3) {
            alert("删除失败，因为您没有操作权限哦~~");
        } else {
            alert("error!");
        }
    }, function (err) {
        console.log(err);
    });
}
/**
 * 批量删除公共函数
 * @param service 请求服务
 * @param url   请求url
 * @param ids   删除id数组
 * @param callback  回调函数
 */
function delBatch(service, url, ids, callback) {
    service.delete(url, {ids: ids}).then(function (res) {
        if (res.code == 0) {
            callback();
        } else if (res.code == 3) {
            alert("批量失败，因为您没有操作权限哦~~");
        } else {
            alert("error!");
        }
    }, function (err) {
        console.log(err);
    });
}
/**
 * 保存数据
 * @param service 请求服务
 * @param url   请求地址
 * @param data  提交数据
 * @param callback  回调函数
 * @param scope
 */
function save(service, url, data, callback, scope) {
    service.add(url, data).then(function (res) {
        if (res.code == 0) {
            console.log(res);
            callback();
        } else if (res.code == 3) {
            alert("表单提交失败，因为您没有操作权限哦~~");
        } else {
            alert("error!");
        }
    }, function (err) {
        console.log(err);
    })
}
/**
 * 根据ID获取信息
 * @param service
 * @param url
 * @param id
 * @param callback
 */
function unique(service, url, id, callback) {
    service.unique(url, id).then(function (res) {
        if (res.code == 0) {
            callback(res);
        } else if (res.code == 3) {
            alert("无法执行更新操作，因为您没有操作权限哦~~");
        } else {
            alert("error!");
        }
    }, function (err) {
        console.log(err);
    })
}
/**
 * 更新信息
 * @param service
 * @param url
 * @param data
 * @param callback
 */
function update(service, url, data, callback) {
    service.add(url, data).then(function (res) {
        if (res.code == 0) {
            callback();
        } else if (res.code == 3) {
            alert("表单提交失败，因为您没有操作权限哦~~");
        } else {
            alert("error!");
        }
    }, function (err) {
        console.log(err);
    })
}
userController.controller('UserCtrl', ['$scope', '$http', 'BaseService', '$rootScope', '$state', '$timeout',
    function ($scope, $http, BaseService, $rootScope, $state, $timeout) {

        //$scope.user = {}; // 双向数据绑定

        //$scope.User = {};
        //$scope.User.user_id=[];
        //$scope.change = function(){
        //    console.log($scope.User);
        //}

        // 列出所有用户
        var getUsersList = function () {
            getList(BaseService, URL.USER_LIST, $scope, "users", $state);
        };
        getUsersList();


        // 获取角色列表
        $scope.$on('getRolesList', function () {
            getList(BaseService, URL.ROLE_LIST, $scope, "roles");
        });

        getList(BaseService, URL.ROLE_LIST, $scope, "roles");

        // 添加用户
        $scope.$on('save', function (data, param) {
            $scope.user.rids = param;
            $scope.user.password = MD5($scope.user.password);
            save(BaseService, URL.USER_ADD, $scope.user, getUsersList, $scope);
        });

        // 删除用户
        $scope.$on('delSingle', function (obj, id) {
            del(BaseService, URL.USER_DELETE, id[0], getUsersList);
        });

        // 批量删除用户
        $scope.$on('delBatch', function (obj, uids) {
            delBatch(BaseService, URL.USER_DEL_BAH, uids, getUsersList);
        });

        // 根据ID获取一个用户
        $scope.$on('unique', function (obj, uid) {
            unique(BaseService, URL.USER_UNIQUE, {uid: uid}, function (data) {
                $scope.user = data.user;
                var rs = data.user.roles;

                $(".modal .select_content li").each(function () {
                    for (var i in rs) {
                        if ($(this).data("id") == rs[i].id) {
                            $(this).addClass("leaf_selected");
                            return;
                        } else {
                            $(this).removeClass("leaf_selected");
                        }
                    }
                });

                $(".select_content").show();
            });
        });

        // 更新用户信息
        $scope.$on("update", function (obj, data) {
            update(BaseService, URL.USER_UPDATE, {
                id: data.obj.id,
                name: data.obj.name,
                password: data.obj.password,
                email: data.obj.email,
                telephone: data.obj.telephone,
                rids: data.ids
            }, function () {
                $('#updateUser').modal('hide');
                getUsersList();
            });
        });
    }
]);

userController.controller('RoleCtrl', ['$scope', '$timeout', 'BaseService', 'PrivilegeService',
    function ($scope, $timeout, BaseService, PrivilegeService) {

        // 列出所有角色
        var getRolesList = function () {
            getList(BaseService, URL.ROLE_LIST, $scope, "roles");
        };
        getRolesList();

        var getPrivList = function () {
            PrivilegeService.getList(URL.PRIV_LIST)
                .then(function (data) {
                    $scope.privileges = data;
                    $timeout(function () {
                        $("#example-advanced").treetable({
                            expandable: true,
                            column: 1,  // column与columnElType 表示字体图标显示在下标为1的td内，column默认值是0
                            columnElType: "td",
                            outerEle: "table",  // 外层父元素
                            innerEle: "tr",         // 内层行数
                            commonClass: "glyphicon",
                            expandClass: "glyphicon-plus",  // 收缩时的CSS样式
                            indenterClass: "glyphicon-minus"    // 展开时的CSS样式
                        });
                    }, 0, false);
                }, function (err) {
                    console.log(err);
                });
        };

        getPrivList();

        $scope.role = {};   // 双向数据绑定

        // 添加角色
        $scope.$on('save', function () {
            save(BaseService, URL.ROLE_ADD, $scope.role, getRolesList, $scope);
        });

        // 删除角色
        $scope.$on('delSingle', function (obj, id) {
            del(BaseService, URL.ROLE_DELETE, id[0], getRolesList);
        });

        // 批量删除角色
        $scope.$on('delBatch', function (obj, rids) {
            delBatch(BaseService, URL.ROLE_DEL_BAH, rids, getRolesList);
        });

        // 角色授权
        $scope.$on('authorization', function (obj, rpids) {
            save(BaseService, URL.ROLE_PRIV, rpids, getRolesList, $scope);
        })

        // 根据ID获取一个角色
        $scope.$on('unique', function (obj, rid) {
            unique(BaseService, URL.ROLE_UNIQUE, {rid: rid}, function (data) {
                $scope.role = data.role;

                var ps = data.role.privileges;
                console.log(ps);
                //alert($("#myTreeSelector li").length);

                jQuery('#myTreeSelector').treetable('expandAll');

                var ids = [];

                $("#myTreeSelector li").each(function(){
                    $(this).removeClass("leaf_selected");
                });

                var select = function(privileges){
                     for (var i in privileges) {
                         ids.push(privileges[i].id);
                         if(privileges[i].children){
                            select(privileges[i].children);
                         }
                    }
                }
                select(ps);
                console.log(ids);
                for (var j in ids) {
                    $("#myTreeSelector li").each(function(){
                        if($(this).data("id") == ids[j]) {
                            $(this).addClass("leaf_selected");
                            return;
                        }
                    });
                }
                //$("#myTreeSelector li").each(function () {
                //    select.apply($(this),ps);
                    //for (var i in ps) {
                    //    if ($(this).data("id") == ps[i].id) {
                    //        console.log($(this).data("id") + ",添加");
                    //        $(this).addClass("leaf_selected");
                    //        return;
                    //    } else {
                    //        console.log($(this).data("id") + ",删除");
                    //        $(this).removeClass("leaf_selected");
                    //    }
                    //
                    //}
                //});
            });
        });

        // 更新角色信息
        $scope.$on("update", function (obj, data) {

            var privileges = data.privileges, pids = [];

            var getPid = function (privilege) {
                for (var p in privilege) {
                    pids.push(p.id);
                    if (p.children) {
                        getPid(p.children);
                    }
                }
            };
            getPid(privileges);


            update(BaseService, URL.ROLE_UPDATE, {
                id: data.obj.id,
                name: data.obj.name,
                description: data.obj.description,
                pids:pids
            }, function () {
                $('#updateRole').modal('hide');
                getRolesList();
            });
        });

    }
]);

userController.controller('privilegeCtrl', ['$scope', '$timeout', 'BaseService', 'PrivilegeService',
    function ($scope, $timeout, BaseService, PrivilegeService) {

        var getPrivList = function () {
            PrivilegeService.getList(URL.PRIV_LIST)
                .then(function (data) {
                    console.log(data);
                    if (data.code == 3) {
                        $scope.message = "您没有操作的权限哦~~~";
                    } else {
                        $scope.privileges = data;
                        $timeout(function () {
                            $("#example-advanced").treetable({
                                expandable: true,
                                column: 1,  // column与columnElType 表示字体图标显示在下标为1的td内，column默认值是0
                                columnElType: "td",
                                outerEle: "table",  // 外层父元素
                                innerEle: "tr",         // 内层行数
                                commonClass: "glyphicon",
                                expandClass: "glyphicon-plus",  // 收缩时的CSS样式
                                indenterClass: "glyphicon-minus"    // 展开时的CSS样式
                            });
                        }, 0, false);
                    }


                }, function (err) {
                    console.log(err);
                });
        };

        getPrivList();

        $scope.privilege = {};

        // 添加权限
        $scope.$on('save', function (data, param) {

            if (param.length != 0) {
                $scope.privilege.parent_id = param;
            }
            save(BaseService, URL.PRIV_ADD, $scope.privilege, getPrivList, $scope);
        });

        // 删除权限
        $scope.$on('delSingle', function (obj, id) {
            del(BaseService, URL.PRIV_DELETE, id[0], getPrivList);
        });

        // 批量删除权限
        $scope.$on('delBatch', function (obj, pids) {
            delBatch(BaseService, URL.PRIV_DEL_BAH, pids, getPrivList);
        });
    }]);


userController.controller('LoginCtrl', ['$scope', '$http', '$state', '$stateParams', '$rootScope', function ($scope, $http, $state, $stateParams, $rootScope) {

    $scope.user = {}; // 双向数据绑定

    // 用户登录
    $scope.login = function () {

        $http.post(URL.USER_LOGIN, $scope.user)
            .success(function (res) {
                if (res.code == 0) {

                    var from = $stateParams["from"];
                    $rootScope.user = $scope.user
                    $state.go(from && from != "login" ? from : $rootScope.defaultPage);
                } else {
                    alert("用户名或密码错误");
                }

            });
    }

    $scope.logout = function () {
        $http.post(URL.USER_LOGOUT, {})
            .success(function (res) {
                if (res.code == 0) {

                    var from = $stateParams["from"];
                    $rootScope.user = $scope.user;
                    $state.go(from && from != "login" ? from : $rootScope.defaultPage);
                } else {
                    alert("ERROR!");
                }

            });
    }
}]);

userController.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
    var strOperate = function (data) {
        for (var i in data) {
            data[i].url = data[i].url.substring(6, data[i].url.lastIndexOf("/"));
            data[i].url = data[i].url.replace(/\//g, ".");
            if (data[i].url == "") {
                data[i].url = ".";
            }
            if (data[i].url == ".user") {
                data[i].url = ".";
            }
            strOperate(data[i].children);
        }
    };
    var getUserPriv = function () {
        $http.get(URL.USER_GETPRIV)
            .success(function (res) {
                var privileges = res.privileges;
                strOperate(privileges);
                $scope.user_privileges = privileges;
            });
    };
    getUserPriv();
}]);